/**
 *       Copyright (c) 2012 Lukas Zaruba
 *
 *   This file is part of Robot Playground.
 *
 *   Robot Playground is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   Robot Playground is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with Robot Playground. If not, see <http://www.gnu.org/licenses/>.
 */
package net.zarubsys.commons.scripting.functions.numbers;

import java.util.List;
import java.util.Random;

import net.zarubsys.commons.scripting.IScriptFunction;
import net.zarubsys.commons.scripting.ParsedStatement;
import net.zarubsys.commons.scripting.ScriptingEnvironment;
import net.zarubsys.commons.scripting.ScriptingException;

/**
 * Based on scripting language from Media Solutions Slovakia, a.s.
 * @author Lukas Zaruba, lukas.zaruba@gmail.com
 */
public class RandomFunction implements IScriptFunction {
	
    private MyRandom rand = new MyRandom();

	public String getName() {
		return "random";
	}

	public int getMinArgsNum() {
		return 1;
	}

	public int getMaxArgsNum() {
		return 2;
	}

	public Object execute(ScriptingEnvironment env, List<ParsedStatement> args) throws ScriptingException {
        Integer min;
        Integer max;
        if (args.size() == 1) {
            max = (Integer) args.get(0).execute(env);
            return Integer.valueOf(rand.nextInt(max.intValue() + 1));
        
        } else if (args.size() == 2) {
            min = (Integer) args.get(0).execute(env);
            max = (Integer) args.get(1).execute(env);
            if (min.intValue() >= max.intValue()) {
                throw new ScriptingException("Illegal arguments: min >= max", env.getCurrentScriptLocator());
            }
            return Integer.valueOf(rand.nextInt(min.intValue(), max.intValue() + 1));
        }
        throw new ScriptingException("Wrong number of arguments: " + args, env.getCurrentScriptLocator());
	}
	
    public static class MyRandom extends Random {
    	
        private static final long serialVersionUID = 1L;

		public int nextInt(int min, int max) {
            if (min < 0 || max < 0) {
                throw new IllegalArgumentException("Both minimal and maximal value must be >= 0 [min=" + min + ", max=" + max + "]");
            }
            int ret;
            do {
            	ret = Math.abs(nextInt(max));
            } while (ret < min);
            return ret;
        }
    }
}
